<?php
/**
 * Created by PhpStorm.
 * User: Jason
 * Date: 2017/7/28
 * Time: 15:07
 */

namespace Api\Service;


use Think\Model;

class SheetFavoriteService
{
    /**
     * 添加用户收藏曲谱
     * @return mixed
     */
    public function addFavSheet($param)
    {
        $model = M('SheetFavorite');
        $map = array(
            'user_id' => $param['uid'],
            'sheet_id' => $param['sheet_id']
        );
        $res = $model->where($map)->select();
        if (!empty($res)) {
            //获取用户当前是否标记为喜欢状态
            if ($res[0]['is_delete'] == 1) {
                $data = array(
                    'is_delete'=>0,
                    'update_time'=>date( 'Y-m-d H:i:s', time())
                );
                $result = $model->where($map)->save($data);
            } else {
                $data = array(
                    'is_delete'=>1,
                    'update_time'=>date( 'Y-m-d H:i:s', time() )
                );
                $result = $model->where($map)->save($data);
            }
            return $result;
        } else {
            $data = $model->create($param);
            if ($data) {
                $param['user_id'] = $param['uid'];
                $param['create_time'] = date( 'Y-m-d H:i:s', time() );
                //添加谱单至收藏表
                $id = $model->add( $param );
                return $id;
            } else {
                E($model->getError());
            }
        }
    }

    /**
     * 获取用户喜欢曲谱
     */
    public function getFavSheet($param)
    {
        $model = M('SheetFavorite');
        $map = array(
            'user_id'=>$param['uid'],
            'is_delete'=>0
        );
        $res = $model->field('sheet_id')->where($map)->select();
        foreach ($res as $val) {
            $sheetIds[] = $val['sheet_id'];
        }
        $cond = array(
            'id' => array('in', $sheetIds)
        );
        $sheetService = new SheetService();
        $sheetList = $sheetService->getSheetListByMap($cond, $param);
        return $sheetList;
    }

}